package com.heima.search.listener;

import com.alibaba.fastjson.JSON;
import com.heima.model.search.pojos.SearchArticleVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class SyncArticleListener {

    //监听文章发布成功到mysql后同步到ES中
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @KafkaListener(topics = "article.es.sync.topic")
    public void onMessage(String message){
        if (StringUtils.isNotBlank(message)){
            return;
        }
        log.info("SyncArticleListener,message={}",message);

        SearchArticleVo searchArticleVo = JSON.parseObject(message, SearchArticleVo.class);
        IndexRequest indexRequest = new IndexRequest("app_info_article");

        indexRequest.id(searchArticleVo.getId().toString())
                .source(message, XContentType.JSON);

        try {
            restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("sync es error={}",e);
        }


    }

}
